<?php
require_once('functions.php');

function GetUsers()
{
        $conn = getConnection();
        return $conn->query('SELECT * FROM User');
}

function GetUser($id)
{
        $conn = getConnection();
        $results = $conn->query("SELECT * FROM User WHERE user_ID=$id");
        $row = $results->fetch_assoc();
        $conn->close();
        return $row;
}

function saveUser(&$row)

{
        $conn = getConnection();
        $row2 = escapeRow($row, $conn);
        
        if (!empty($row['user_ID']))
        	$sql =  "UPDATE User SET firstName='$row2[firstName]', secondName='$row2[secondName]', status_ID='$row2[status_ID]' WHERE user_ID=$row2[user_ID]";
        else
        	$sql = "INSERT INTO User VALUES (NULL, '$row2[firstName]', '$row2[secondName]','$row2[status_ID]', NULL, NOW(),NULL)";
        $results = $conn->query($sql);
        $error = $conn->error;
        
        if(empty($row['user_ID']) && empty($error))
        {
                $row['user_ID'] = $conn->insert_id;
        }

        $conn->close();
       
        return $error == '' ? true : array('SQL Error' => $error);
}


function deleteUser($id)
{
		$conn = getConnection();
		$conn->query("DELETE FROM User WHERE user_ID = $id");
		$autoInc = $id - 1;
		$conn->query("ALTER TABLE User AUTO_INCREMENT = $autoInc");
		$conn->close();
		header('Location: index.php');
}	

function getDistinctType()
{
	$conn = getConnection();
	return $conn->query('SELECT DISTINCT type FROM User');
}

function blankUser()
{
	return array('user_ID' => null, 'firstName' => null, 'secondName' => null);
} 
